#include "bsp_buzzer.h"

#include "adc.h"
#include "bsp_def.h"
#include "FreeRTOS.h"
#include "cmsis_os.h"
#include "bsp_def.h"
#include "ax_oled_1305.h"

void BSP_Volte_Init() { 
     HAL_ADC_Start(BSP_BATTERY_ADC);  // 开启ADC用于电压读取 
}

void LedRedBlink(uint16_t delay, uint8_t times) {
    for (uint8_t i = 0; i < times; i++) {
        HAL_GPIO_WritePin(BSP_LED_RED_GPIO, BSP_LED_RED_PIN, BSP_LED_ON);  // LED3 低电平有效
        osDelay(delay);
        HAL_GPIO_WritePin(BSP_LED_RED_GPIO, BSP_LED_RED_PIN, BSP_LED_OFF);  // LED3 低电平有效
        if (i != times - 1){
            osDelay(delay);
        }
    }
}

void LedGreenBlink(uint16_t delay, uint8_t times) {
    for (uint8_t i = 0; i < times; i++) {
        HAL_GPIO_WritePin(BSP_LED_GREEN_GPIO, BSP_LED_GREEN_PIN, BSP_LED_ON);  // LED4 低电平有效
        osDelay(delay);
        HAL_GPIO_WritePin(BSP_LED_GREEN_GPIO, BSP_LED_GREEN_PIN, BSP_LED_OFF);  // LED3 低电平有效
        if (i != times - 1){
            osDelay(delay);
        }
    }
}

void BuzzerBeep(uint16_t delay, uint8_t times) {
    for (uint8_t i = 0; i < times; i++) {
        HAL_GPIO_WritePin(BSP_BUZZER_GPIO, BSP_BUZZER_PIN, BSP_BUZZER_ON);  // SPEAKER 高电平有效
        osDelay(delay);
        HAL_GPIO_WritePin(BSP_BUZZER_GPIO, BSP_BUZZER_PIN, BSP_BUZZER_OFF);  // SPEAKER close
        if (i != times - 1){
            osDelay(delay);
        }
    }
}

float ADC_ToVoltage(uint16_t adc_value) {
    // STM32F1 ADC为12位，最大值为4095
    // 参考电压一般为3.3V
    const float VREF = 3.3f;
    return (adc_value * VREF) / 4095.0f;
}

float GetBatteryVoltage() {
    HAL_ADC_Start(BSP_BATTERY_ADC);
    HAL_ADC_PollForConversion(BSP_BATTERY_ADC, 10);     // 等待转换完成
    volatile uint32_t adc_value = HAL_ADC_GetValue(BSP_BATTERY_ADC);
    return ADC_ToVoltage(adc_value * 11.0);  // 10:1分压 
}
float BSP_Volte_Loop(){
    HAL_ADC_Start(BSP_BATTERY_ADC);
    HAL_ADC_PollForConversion(BSP_BATTERY_ADC, 10);     // 等待转换完成
    volatile uint32_t adc_value = HAL_ADC_GetValue(BSP_BATTERY_ADC);
    return ADC_ToVoltage(adc_value * 11.0);  // 10:1分压 
}

void BSP_OLED_Init() {
    AX_OLED_Init();  // OLED初始化
    AX_OLED_ClearScreen();
}

void BSP_OLED_Welcome() {
    char* ch = "hello motor!";
    AX_OLED_DispStr(0, 0, (uint8_t*)ch, 0);  // OLED指定位置显示ASCII字符串（6X8）
}

void BSP_OLED_ShowVolte(){
    AX_OLED_DispFloat(0, 2, GetBatteryVoltage(), 2, 2, 0);
    uint8_t ch = 'v';
    AX_OLED_DispChar(32, 7, ch, 1);
    
}
   